//
//  FlywightFactory.swift
//  FlyweightPattern
//
//  Created by LY on 2017/11/5.
//  Copyright © 2017年 DesignPatterns. All rights reserved.
//

import Foundation
class Owner{
    var name : String
    var city : String
    init(name:String,city:String) {
        self.name = name
        self.city = city
    }
    func copy(with zone: NSZone? = nil) -> Owner {
        return Owner(name: name, city: city)
    }
}

class Flyweight {
    private let extrinsicOwner:Owner
    private var intrinsicOwner:Owner?
    init(owner:Owner) {
        self.extrinsicOwner = owner
    }
    var name :String{
        get{
            return intrinsicOwner?.name ?? extrinsicOwner.name
        }
        set(value){
            decoupleFormExtrinsic()
            intrinsicOwner?.name = value
        }
    }
    var city:String{
        get{
            return intrinsicOwner?.city ?? extrinsicOwner.city
        }
        set(value){
            decoupleFormExtrinsic()
            intrinsicOwner?.city = value
        }
    }
    private func decoupleFormExtrinsic(){
        if intrinsicOwner == nil {
            intrinsicOwner = extrinsicOwner.copy(with: nil)
        }
    }
}

class FlyweightFactoryCOW {
    class func createFlyweight() -> Flyweight{
        return Flyweight(owner: Owner(name: "Anonymous", city: "AnyWhere"))
    }
}
